using UnityEditor;
using UnityEngine;

namespace QFramework.Framework.ResKit.Res
{
    public class AssetRes : Res
    {
        private readonly string _ownerBundleName;

        private ResLoader _resLoader = new();

        public AssetRes(string assetName, string ownerBundleName)
        {
            Name = assetName;

            _ownerBundleName = ownerBundleName;

            State = ResState.Waiting;
        }

        public override bool LoadSync()
        {
            State = ResState.Loading;

            var ownerBundle = _resLoader.LoadSync<AssetBundle>(_ownerBundleName);

            if (ResMgr.IsSimulationModeLogic)
            {
#if UNITY_EDITOR
                var assetPaths = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(_ownerBundleName, Name);
                Asset = AssetDatabase.LoadAssetAtPath<Object>(assetPaths[0]);
#endif
            }
            else
            {
                Asset = ownerBundle.LoadAsset(Name);
            }

            State = ResState.Loaded;

            return Asset;
        }

        public override void LoadAsync()
        {
            State = ResState.Loading;

            _resLoader.LoadAsync<AssetBundle>(_ownerBundleName, ownerBundle =>
            {
                if (ResMgr.IsSimulationModeLogic)
                {
#if UNITY_EDITOR
                    var assetPaths = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(_ownerBundleName, Name);

                    Asset = AssetDatabase.LoadAssetAtPath<Object>(assetPaths[0]);
                    State = ResState.Loaded;
#endif
                }
                else
                {
                    var assetBundleRequest = ownerBundle.LoadAssetAsync(Name);

                    assetBundleRequest.completed += operation =>
                    {
                        Asset = assetBundleRequest.asset;
                        State = ResState.Loaded;
                    };
                }
            });
        }

        protected override void OnReleaseRes()
        {
            if (Asset is not GameObject) Resources.UnloadAsset(Asset);

            Asset = null;

            _resLoader.ReleaseAll();
            _resLoader = null;

            ResMgr.Instance.SharedLoadedReses.Remove(this);
        }
    }
}